package com.play.ballen.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.xuexiang.xupdate.proxy.IUpdateHttpService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 描述：文件下载
 */
public class OKHttpUpdateHttpService extends Service implements IUpdateHttpService {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void asyncGet(@NonNull String url, @NonNull Map<String, Object> params, @NonNull Callback callBack) {

    }

    @Override
    public void asyncPost(@NonNull String url, @NonNull Map<String, Object> params, @NonNull Callback callBack) {

    }

    @Override
    public void download(@NonNull String url, @NonNull final String path, @NonNull final String fileName, @NonNull final DownloadCallback callback) {
        callback.onStart();
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(180, TimeUnit.SECONDS)
                .connectTimeout(180, TimeUnit.SECONDS)
                .build();
        final Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("文件下载","异常1");
                callback.onError(e);
            }

            @Override
            public void onResponse(Call call, Response response)  {
                try {
                    File file = new File(path + File.separator + fileName);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    if (response != null) {
                        long length = response.body().contentLength();
                        long sum = 0;
                        InputStream is = response.body().byteStream();
                        FileOutputStream fos = new FileOutputStream(file);
                        int len = 0;
                        byte[] buffer = new byte[2048];
                        while (-1 != (len = is.read(buffer))) {
                            fos.write(buffer, 0, len);
                            fos.flush();
                            if (length > 0) {
                                sum += len;
                                callback.onProgress((int) (sum * 100 / length), length);
                            }
                        }
                        fos.close();
                        is.close();
                        callback.onSuccess(file);
                    }
                }catch (Exception e){
                    Log.e("文件下载","异常2");
                    callback.onError(e);
                }
            }
        });
    }

    @Override
    public void cancelDownload(@NonNull String url) {

    }
}
